package bb.lanxing.lib.devices.utils;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import bb.lanxing.lib.devices.core.dfu.IDfuAdapter;
import bb.lanxing.lib.devices.core.utils.CharacteristicValueHelper;

public abstract class DeviceActionReceiver extends BroadcastReceiver {
    private boolean isRegistered;

    protected abstract boolean handleBroadcast(Intent intent);

    @Override
    public void onReceive(Context context, Intent intent) {
        boolean z;
        try {
            z = handleBroadcast(intent);
        } catch (Exception unused) {
            z = true;
        }
        if (!z || !isOrderedBroadcast()) {
            return;
        }
        abortBroadcast();
    }

    public void registerReceiver(Context context) {
        if (this.isRegistered || context == null) {
            return;
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("ACTION_ACTION_SEND_CMD");
        intentFilter.addAction("ACTION_REQUEST_BATTERY");
        intentFilter.addAction("ACTION_HEARTRATE_BODY_LOCATION");
        intentFilter.addAction("ACTION_REQUEST_DEVICE_INFORMATION");
        intentFilter.addAction("ACTION_READ_DEVICE_INFORMATION");
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        intentFilter.addAction(IDfuAdapter.ACTION_DFU_MODE_SETUP);
        intentFilter.addAction(CharacteristicValueHelper.ACTION_READ_CHARACTERISTIC);
        intentFilter.setPriority(998);
        intentFilter.addAction("ACTION_READ_DEVICE_INFORMATION");
        intentFilter.addAction("ACTION_READ_DEVICE_INFORMATION_RESULT");
        context.registerReceiver(this, intentFilter, Context.RECEIVER_EXPORTED);
        this.isRegistered = true;
    }

    public void unregisterReceiver(Context context) {
        if (!this.isRegistered || context == null) {
            return;
        }
        context.unregisterReceiver(this);
        this.isRegistered = false;
    }
}
